package com.twu.biblioteca;

import java.util.*;

/**
 * Created by kathy on 17/04/14.
 */
public class UserLogin implements IUserLogin, Action {

    private List<User> userList;
    private IConsoleReader consoleReader;
    private IConsoleWriter consoleWriter;

    void setConsoleReader(IConsoleReader consoleReader){
        this.consoleReader = consoleReader;
    }

    void setConsoleWriter(IConsoleWriter consoleWriter){
        this.consoleWriter = consoleWriter;
    }

    public UserLogin(List<User> userList){
        this.userList = userList;
        consoleReader = new ConsoleReader();
        consoleWriter = new ConsoleWriter();
    }

    public void execute(){
        if(BibliotecaApp.currentUser == null)
            BibliotecaApp.currentUser = login();
        else
            consoleWriter.println("You are currently logged in with Id: " + BibliotecaApp.currentUser.getId());
    }

    public User login(){
        consoleWriter.println("Please login to continue your option.\n User id: ");
        String userId = consoleReader.readInput();
        consoleWriter.println("Password: ");
        String password = consoleReader.readInput();

        User user =  checkUserIdAndPassword(userId, password);

        if(user == null)
            consoleWriter.println("Invalid user id and password!");
        else
            consoleWriter.println("Your login is successful!");

        return user;
    }

    public User checkUserIdAndPassword(String id, String password){

        id = id.toLowerCase().trim();
        password = password.toLowerCase().trim();

        for(User user : userList){

            String userId = user.getId().toString().toLowerCase();
            String userPassword = user.getPassword().toString().toLowerCase();

            if(userId.equals(id) && userPassword.equals(password)){
                return user;
            }
        }
        return null;
    }
}
